<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2023-09-21 15:06:27
 * @LastEditors: 甯左龙 1173405584@qq.com
 * @Description:
 * @FilePath: \wms-v2\src\ve\components\widget.vue
 * CIMC-V2
-->
<template>
  <template v-if="!hasPreview">
    <draggable
      class="relative draggable-canvas"
      v-bind="dragOptions"
      :component-data="{
        tag: 'div',
        type: 'transition-group',
        name: !drag ? 'flip-list' : null,
      }"
      item-key="_id"
      :list="list"
      @change="draggableChange"
      @end="draggableEnd"
      @start="draggableStart"
    >
      <template #item="{ element }">
        <div
          class="component-box relative"
          :class="[
            { selectActive: element._id == getSelectModuleId },
            element.type,
            element.type == 'uiGrid' ? element.extension.height.value : '',
            element.type.indexOf('Chart') !== -1 ? 'flex-auto' : '',
            element.type == 'uiChartQuotaBox' ? 'h-full' : '',
            [
              'uiBydPage',
              'uiBgBox',
              'uiBydModelTitle',
              'uiBydInventory',
              'uiBydMonitor',
              'uiBydShipment',
              'uiBydUtilize',
              'uiSanxiaModel1',
              'uiSanxiaModel2',
              'uiSanxiaModel3',
              'uiSanxiaModel4',
            ].includes(element.type)
              ? 'h-full'
              : '',
            element.type == 'uiFlexbox' ? 'overflow-y-auto overflow-x-hidden' : '',
          ]"
          :style="{ padding: '0px' }"
          :data-com-id="element._id"
          @click.stop="selectCommand(element)"
        >
          <div v-if="element._id == getSelectModuleId" class="item-drag">
            <vui-icon icon="drag-move-2-line" />
          </div>
          <div
            v-if="element._id == getSelectModuleId && element.type === 'uiForm'"
            class="item-CopyKey cursor-pointer"
            title="点击即可复制表单 key"
            @click="copyFormKeys(element)"
          >
            <vui-icon icon="file-copy-line" />
          </div>
          <div v-if="element._id == getSelectModuleId" class="item-remove" @click="removeComponent(element)">
            <vui-icon icon="delete-bin-line" />
          </div>
          <component :is="element.type" :info="element" />
        </div>
      </template>
    </draggable>
  </template>
  <template v-else>
    <div class="relative draggable-canvas preview-canvas h-full">
      <div
        v-for="element in list"
        :key="element._id"
        class="component-box relative"
        :style="{ padding: '0px' }"
        :class="[
          element.type,
          element.type.indexOf('Chart') !== -1 ? 'flex-auto' : '',
          element.type == 'uiChartQuotaBox' ? 'h-full' : '',
          element.type == 'uiFlexbox' ? 'overflow-y-auto overflow-x-hidden' : '',
          [
            'uiBydPage',
            'uiBgBox',
            'uiBydModelTitle',
            'uiBydInventory',
            'uiBydMonitor',
            'uiBydShipment',
            'uiBydUtilize',
            'uiSanxiaModel1',
            'uiSanxiaModel2',
            'uiSanxiaModel3',
            'uiSanxiaModel4',
          ].includes(element.type)
            ? 'h-full'
            : '',
          { hidden: element.extension && element.extension.hidden && element.extension.hidden.value },
        ]"
        :data-com-id="element._id"
      >
        <!-- <lazyComponent>
          <template #placeholder>
            <div class="bg-gray-200 flex items-center justify-center" :style="{ height: height + 'px', width: '100%' }">
              <div class="animate-ping h-10 w-10 rounded-full bg-white opacity-75"></div>
            </div>
          </template> -->
        <component :is="element.type" :info="element">
          <slot></slot>
        </component>
        <!-- </lazyComponent> -->
      </div>
    </div>
  </template>
</template>
<script>
  import { defineComponent } from 'vue'
  import draggable from 'vuedraggable'
  import elements from '@ve/elements/view'
  import { DiyMixin } from '@ve/mixin'
  import { setModels } from '@ve/utils/utils'
  import { saveRevocation } from '@ve/utils/revocationPageInfo'
  import cloneDeep from 'lodash/cloneDeep'
  import forOwn from 'lodash/forOwn'
  import { componentId } from '@/utils/unique'
  import { clipboard } from '@ve/utils/clipboard'
  import lazyComponent from '@ve/components/lazyComponent'
  import border from '../common/tailwindcss/border'

  //接收赋值的数据
  let selectData = {}
  export default defineComponent({
    name: 'Widget',
    components: {
      draggable,
      lazyComponent,
      ...elements,
    },
    mixins: [DiyMixin],
    inject: {
      hasPreview: { default: false },
    },
    props: {
      list: {
        required: true,
        type: Array,
        default: function () {
          return []
        },
      },
    },
    data() {
      return {
        drag: false,
        selectData: {},
      }
    },
    computed: {
      dragOptions() {
        return {
          animation: 200,
          group: 'model',
          disabled: false,
          ghostClass: 'ghost',
          handle: '.item-drag',
        }
      },
    },
    created() {},
    mounted() {
      const self = this
      // document.onkeydown = function (event) {
      //   //预览模式不触发
      //   if (self.$store.getters['preview/getHasPreview']) {
      //     return
      //   }
      //   //ctrl + c
      //   // console.log('复制', event.ctrlKey, event.altKey, event.keyCode == 67)
      //   if (event.ctrlKey && event.altKey && event.keyCode == 67) {
      //     console.log('复制组件')
      //     self.copynode.call(self)
      //   }
      //   //ctrl + v
      //   if (event.ctrlKey && event.altKey && event.keyCode == 86) {
      //     self.pastnode.call(self)
      //   }
      //   //ctrl + f
      //   if (event.ctrlKey && event.keyCode == 70) {
      //     event.preventDefault()
      //     self.$store.dispatch('diySearchComsModal/modalSwitch', true)
      //   }
      // }
    },
    methods: {
      draggableChange(event) {
        if (event.added) {
          //存储组件
          saveRevocation.call(this)

          setModels(this.getPageModules)
        }
      },
      draggableStart(event) {
        //存储组件
        saveRevocation.call(this)

        console.log(event)
        this.drag = true
      },
      //拖动结束
      draggableEnd(event) {
        //存储组件
        saveRevocation.call(this)

        console.log(event)
        this.drag = false
      },
      //选择组件进行记录
      selectCommand(item) {
        if (this.getSelectModuleId === item._id) {
          this.$store.dispatch('diy/setSelectModule', {})
          this.$store.dispatch('diy/setSelectModuleId', '')
          return
        }

        this.$store.dispatch('diy/setSelectModuleId', item._id)
        this.$store.dispatch('diy/setSelectModule', item)
      },
      //删除组件
      removeComponent(item) {
        this.$confirm('此操作将删除组件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            //存储组件
            saveRevocation.call(this)
            //删除组件
            this.$store.dispatch('diy/removeModule', item)
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          })
          .catch((e) => {
            console.log(e)
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      // 复制表单组件 key
      copyFormKeys(item) {
        let keysStr = ''
        console.log('item ---- ', item)
        forOwn(item.data?.formData, (val, key) => {
          if (keysStr.length) {
            keysStr += ','
          }
          keysStr += key
        })
        clipboard(keysStr)
      },
      //复制
      copynode() {
        if (!this.getSelectModule._id) {
          return
        }
        //获取点击的节点
        selectData = cloneDeep(this.getSelectModule)
      },
      //粘贴改变ID
      setNodeChangeId(selectData) {
        const node = selectData
        if (node._id) {
          node._id = node.type + '_' + componentId(6)
        }
        if (node.list) {
          for (let i = 0; i < node.list.length; i++) {
            this.setNodeChangeId(node.list[i])
          }
        }
        if (node.pageModules) {
          for (let i = 0; i < node.pageModules.length; i++) {
            this.setNodeChangeId(node.pageModules[i])
          }
        }
        return node
      },
      //粘贴
      setnode(pageModules, targetData) {
        for (let i = 0; i < pageModules.length; i++) {
          //如果是底层直接执行添加
          if (pageModules[i]._id === targetData._id) {
            const node = this.setNodeChangeId(cloneDeep(selectData))
            //node._id = node.type + '_' + componentId(6)
            if (pageModules[i].list) {
              pageModules[i].list.push(node)
            } else {
              pageModules.push(node)
            }
            break
          }
          //如果是list
          if (pageModules[i].list) {
            this.setnode(pageModules[i].list, targetData)
          }
        }
      },
      //粘贴执行事件
      pastnode() {
        if (!selectData._id) {
          return
        }
        const pageModules = this.getPageModules
        const selectNode = cloneDeep(this.getSelectModule)
        if (!selectNode._id) {
          const node = cloneDeep(selectData)
          node._id = node.type + '_' + componentId(6)
          pageModules.push(node)
        } else {
          if (selectNode._id === selectData._id) {
            //在本级别复制
            this.setnode(pageModules, selectData)
          } else {
            //其他级别复制
            this.setnode(pageModules, selectNode)
          }
        }
        this.$store.dispatch('diy/setPageModules', pageModules)
        //存储组件
        saveRevocation.call(this)
      },
    },
  })
</script>

<style scoped>
  .uiTable {
    width: 100%;
  }
</style>
